const express = require("express");
const router = express.Router();
const ResponseHelper = require("../ResponseHelper");
const RecordInfoServer = require("../../servers/RecordInfo");

router.post("/", async (req, res, next) => {
  try {
    var params = req.body;
    console.log("+++++++++++++++++++++++上传的视频uploadVideo:", params);
    if (!params.UUID) {
      console.log("+++++++++++++++++++++++没有uuid");
      return;
    }
    if (!params.FileName) {
      console.log("+++++++++++++++++++++++没有FileName");
      return;
    }
    if(!params.SaveSubDir){
      console.log("+++++++++++++++++++++++没有SaveSubDir");
      return;
    }
    let id
    const SaveSubDir_arrs = params.SaveSubDir.split("/");
    if (SaveSubDir_arrs.length > 0) {
      id = SaveSubDir_arrs[SaveSubDir_arrs.length - 2];
    }
    const videoUrl = `http://${req.headers.host}/pubilc/uploads/${params.SaveSubDir}/${params.FileName}`;
    const videoInfo = {
      url: videoUrl,
      pid: params.UUID,
      id,
      isVideo:true
    };
    console.log("+++++++++++++++++++++++保存的视频信息videoInfo:",videoInfo);
    const record = await RecordInfoServer.getById(params.UUID);
    const videos = record.videos;
    let videoVal;
    if (videos) {
      videoVal = JSON.parse(videos);
      videoVal.push(videoInfo);
    } else {
      videoVal = [];
      videoVal.push(videoInfo);
    }
    const updateVideo = JSON.stringify(videoVal);
    const updateReportRes = await RecordInfoServer.update(params.UUID, {
      videos: updateVideo,
    });
    if (updateReportRes.length > 0) {
      ResponseHelper.sendData(videoUrl, res);
    } else {
      ResponseHelper.sendErr(`上传失败!`, res);
    }
  } catch (err) {
    console.log("+++++++++++++++++++++++err", err);
    ResponseHelper.sendErr(err, res);
  }
});
module.exports = router;
